﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CKS2320.Common.Utils
{
    /// <summary>
    /// socket连接
    /// </summary>
    public class SocketUtils
    {
        private string IpAddress;
        private IPEndPoint IpPoint;
        Socket socketSend;//= new Socket (AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Connect(string ip, int port)
        {
            try
            {
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this.IpAddress = ip;
                this.IpPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                IPAddress IP = IPAddress.Parse(IpAddress);
                //socketSend.Bind(IpPoint);
                //socketSend.Listen(1024);
                socketSend.Connect(IpPoint);
                //Thread handleSocket = new Thread(new ThreadStart(HandleSocket));
                //handleSocket.Start();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public void Close()
        {
            this.socketSend.Close();
        }
        /// <summary>
        /// 监听链接
        /// </summary>
        public bool HandleSocket()
        {


            bool blockingState = socketSend.Blocking;
            try
            {
                byte[] tmp = new byte[1];
                socketSend.Blocking = false;
                socketSend.Send(tmp, 0, 0);
                return false;
            }
            catch (SocketException e)
            {
                // 产生 10035 == WSAEWOULDBLOCK 错误，说明被阻止了，但是还是连接的
                if (e.NativeErrorCode.Equals(10035))
                    return false;
                else
                    return true;
            }
            finally
            {
                socketSend.Blocking = blockingState;    // 恢复状态
            }


        }
        /// <summary>
        /// 处理Socket信息
        /// </summary>
        /// <param name="obj">新建连接创建新Socket对象</param>
        private void ProcessSocket(object obj)
        {
            Socket currSocket = (Socket)obj;
            try
            {
                byte[] recvBytess = new byte[1048576];
                int recbytes;
                recbytes = currSocket.Receive(recvBytess, recvBytess.Length, 0);
                if (recbytes > 0)
                {
                    var contentStr = Encoding.UTF8.GetString(recvBytess, 0, recbytes);
                }
            }
            catch (Exception ex)
            {
                //log
            }
        }
        /// <summary>
        /// Socket 发送消息
        /// </summary>
        /// <param name="strmsg">消息</param>
        public void SendVarMessage(string strmsg)
        {
            try
            {

                byte[] buffer = new byte[1024];
                buffer = Encoding.UTF8.GetBytes(strmsg + "\r");
                //byte[] msg = System.Text.Encoding.UTF8.GetBytes(strmsg);
                this.socketSend.Send(buffer);
            }
            catch (Exception ex)
            {
                this.socketSend.Close();
            }
        }
        /// <summary>
        /// Socket 发送心跳包
        /// </summary>
        /// <param name="strmsg">消息</param>
        public void SendBbuffer()
        {
            try
            {
                byte[] buffer = new byte[1];
                this.socketSend.Send(buffer,0,0);
            }
            catch (Exception ex)
            {
                this.socketSend.Close();
            }
        }


        /// <summary>
        /// Socket 消息回传
        /// </summary>
        /// <returns></returns>
        public string ReceiveMessage()
        {
            try
            {
                byte[] msg = new byte[1048576];
                int recv = socketSend.Receive(msg);
                return System.Text.Encoding.UTF8.GetString(msg, 0, recv);
            }
            catch (Exception ex)
            {
                this.socketSend.Close();
                return KeyenceWhileResultEnum.error.ToString();
            }
        }
    }
}
